package com.omega.controller;

import java.util.Iterator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.omega.common.utils.Utils;
import com.omega.constants.ApplicationConstants;
import com.omega.entity.Brand;
import com.omega.service.BrandService;
import com.omega.vo.BrandListVO;
import com.omega.vo.EntityListVO;

@Controller
@RequestMapping(value = "/admin/brand")
public class BrandController {
	
	@Autowired
	BrandService brandService;
	
	@RequestMapping(value = "/addNewBrand", method = RequestMethod.GET)
	public String showAddNewBrandForm(Model model) {
		BrandListVO brandListVO = EntityListVO.getBrandListVO();
		model.addAttribute(ApplicationConstants.BRAND_LIST_VO, brandListVO);
		return ApplicationConstants.ADD_NEW_BRAND_VIEW;
	}
	
	@RequestMapping(value = "/addNewBrand", method = RequestMethod.POST)
	public String submitNewBrandForm(@ModelAttribute(ApplicationConstants.BRAND_LIST_VO) BrandListVO brandListVO) {
		for (Iterator<Brand> iterator = brandListVO.getBrandList().iterator(); iterator.hasNext();) {
			Brand brand = (Brand) iterator.next();
			if(!(StringUtils.isEmpty(brand.getBrandName())))
			brandService.addBrand(brand);
		}
		return ApplicationConstants.REDIRECT_BRANDS_VIEW;
	}

	@RequestMapping(value = "/viewBrands", method = RequestMethod.GET)
	public String viewAllBrands(Model model){
		model.addAttribute(ApplicationConstants.BRAND_NAMES, brandService.loadAllBrands());
		return ApplicationConstants.BRAND_NAMES_VIEW;
	}
	
	@RequestMapping(value = "/editBrand/{brandID}", method = RequestMethod.GET)
	public String showEditBrandForm(@PathVariable("brandID") String brandId, Model  model) {
		System.out.println("BrandID in Controller: " + brandId);
		Brand brand = brandService.loadById(Integer.parseInt(brandId));
		System.out.println("BrandName: " + brand.getBrandName());
		model.addAttribute("yearMap", Utils.getYearsMap());
		model.addAttribute("monthMap", Utils.getMonthsMap());
		model.addAttribute(ApplicationConstants.BRAND_OBJ, brand);
		return ApplicationConstants.EDIT_BRAND_VIEW;
	}
	
	@RequestMapping(value = "/editBrand/{brandId}", method = RequestMethod.POST)
	public String submitEditBrandForm(@PathVariable("brandId") String brandId, @ModelAttribute(ApplicationConstants.BRAND_OBJ) Brand brand){
		System.out.println("Brand name in form submit: " + brand.getBrandName() + " : " + brand.getbrandId());
		brandService.updateBrand(brand);		
		return ApplicationConstants.REDIRECT_BRANDS_VIEW;
	}
	
}
